package com.maxlen.admin.security;

import com.maxlen.admin.entity.bo.LoginDetailsBo;
import com.maxlen.common.constant.MemberConstant;
import com.maxlen.common.utils.JwtUtils;
import com.maxlen.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 前端每次请求都拦截，判断是否登录
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwtToken = request.getHeader("token");
        if(JwtUtils.checkToken(jwtToken)){
            String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(jwtToken);

            LoginDetailsBo loginDetailsBo = RedisUtils.get(redisTemplate, MemberConstant.MEMBER_LOGIN + memberIdByJwtToken, LoginDetailsBo.class);
            if(!ObjectUtils.isEmpty(loginDetailsBo)){
                if(ObjectUtils.isEmpty(SecurityContextHolder.getContext().getAuthentication())){
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginDetailsBo, null, loginDetailsBo.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }

        filterChain.doFilter(request,response);
    }
}
